package com.boyinet.activation.security.handler;


import com.boyinet.activation.util.R;
import com.boyinet.activation.util.ResponseUtil;
import com.boyinet.activation.util.TokenManager;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 退出处理器
 *
 * @author lengchunyun
 */
public class TokenLogoutHandler implements LogoutHandler {

    private final TokenManager tokenManager;
    private final StringRedisTemplate stringRedisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager, StringRedisTemplate stringRedisTemplate) {
        this.tokenManager = tokenManager;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //1 从header里面获取token
        //2 token不为空，移除token，从redis删除token
        String token = request.getHeader("token");
        if (token != null) {
            //移除
            tokenManager.removeToken(token);
            //从token获取用户名
            String username = tokenManager.getUserFromToken(token);
            stringRedisTemplate.delete(username);
        }
        ResponseUtil.out(response, R.ok());
    }
}
